package com.knife.blog.logic.impl;

import com.knife.web.tools.DbPageList;
import com.knife.web.tools.IPageList;
import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.BlogNewsDir;
import com.knife.blog.domain.BlogNewsDoc;
import com.knife.blog.logic.BlogDirService;
import com.knife.blog.logic.BlogNewsDocService;
import com.knife.blog.logic.BlogUserService;
import com.knife.blog.logic.CurrentUser;
import com.knife.blog.logic.HTMLGenerater;
import com.knife.blog.service.Config;
import com.knife.blog.util.BlogFileUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;

public class BlogCoreServiceImpl extends DAOSupportService
        implements BlogNewsDocService, BlogDirService {

    private static final Logger logger = (Logger) Logger.getLogger(BlogCoreServiceImpl.class.getName());
    private BlogUserService userService = BlogUserServiceImpl.getInstance();
    private static BlogCoreServiceImpl singleton = new BlogCoreServiceImpl();
    private boolean keywordCanSplit = false;

    public static BlogCoreServiceImpl getInstance() {
        return singleton;
    }

    public boolean addBlogNewsDir(BlogNewsDir dir) {
        boolean ret = false;
        dir.setInputuser(CurrentUser.getActiveUser().getUserName());
        BlogInfo bloinfo = this.userService.getUserBlog(dir.getInputuser());
        this.userService.blogInfoChange(bloinfo);
        ret = this.dao.save(dir);
        HTMLGenerater.saveLeftArticalClassifyToHTML(bloinfo);
        return ret;
    }

    public boolean delBlogNewsDir(String cid) {
        boolean ret = false;
        BlogNewsDir dir = getBlogNewsDir(cid);
        ret = this.dao.del(getBlogNewsDir(cid));
        BlogInfo bloinfo = this.userService.getUserBlog(dir.getInputuser());
        HTMLGenerater.saveLeftArticalClassifyToHTML(bloinfo);
        return ret;
    }

    public int delUserBlogNewsDir(String username) {
        int ret = 0;
        String scope = "1=1";
        Collection<Object> paras = new ArrayList<Object>();
        if ((username != null) && (!("".equals(username)))) {
            scope = scope + " and inputuser=? ";
            paras.add(username);
        }
        DbPageList pList = new DbPageList(BlogNewsDir.class, scope, paras);
        pList.doList(0, -1);
        if (pList.getResult() != null) {
            List newsDirlist = pList.getResult();
            for(int i=0;i<newsDirlist.size();i++){
                BlogNewsDir blogdir=(BlogNewsDir)newsDirlist.get(i);
                boolean isdel=this.delBlogNewsDir(blogdir.getCid());
                if(isdel){
                    ret++;
                }
            }
        }
        return ret;
    }

    public int batchDelBlogNewsDir(String[] cids) {
        int ret = 0;
        for (int i = 0; i < cids.length; ++i) {
            if (delBlogNewsDir(cids[i])) {
                ++ret;
            }
        }
        return ret;
    }

    public boolean updateBlogNewsDir(BlogNewsDir dir) {
        boolean ret = false;
        ret = this.dao.update(dir);
        BlogInfo bloinfo = this.userService.getUserBlog(dir.getInputuser());
        HTMLGenerater.saveLeftArticalClassifyToHTML(bloinfo);
        return ret;
    }

    public int batchDelBlogNewsDoc(String[] cids) {
        int ret = 0;
        for (int i = 0; i < cids.length; ++i) {
            if (delBlogNewsDoc(cids[i])) {
                ++ret;
            }
        }
        return ret;
    }

    public BlogNewsDir getBlogNewsDir(String cid) {
        return ((BlogNewsDir) this.dao.get(BlogNewsDir.class, cid));
    }

    public IPageList queryBlogNewsDir(String username, int currentPage, int pageSize) {
        String scope = "inputuser=? and (parentsn='' or parentsn is null)";
        Collection<Object> paras = new ArrayList<Object>();
        paras.add(username);
        DbPageList pList = new DbPageList(BlogNewsDir.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    public IPageList getChildDirs(BlogNewsDir dir, int currentPage, int pageSize) {
        String scope = "parentsn=?";
        Collection<Object> paras = new ArrayList<Object>();
        paras.add(dir.getCid());
        DbPageList pList = new DbPageList(BlogNewsDir.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    public BlogNewsDoc getBlogNewsDoc(String cid) {
        return ((BlogNewsDoc) this.dao.get(BlogNewsDoc.class, cid));
    }

    public IPageList queryBlogNewsDoc(String username, int currentPage, int pageSize) {
        return queryBlogNewsDoc(username, null, null, null, null, null, currentPage,
                pageSize);
    }

    public IPageList queryBlogNewsDoc(String username, Date date1, Date date2, int currentPage, int pageSize) {
        return queryBlogNewsDoc(username, null, null, date1, date2, null, currentPage, pageSize);
    }

    public IPageList queryBlogNewsDoc(String username, String circleSn, String dirId, Date date1, Date date2, String query, int currentPage, int pageSize) {
        String scope = "1=1";
        Collection<Object> paras = new ArrayList<Object>();
        if ((username != null) && (!("".equals(username)))) {
            scope = "inputuser=?";
            paras.add(username);
        }
        if ((circleSn != null) && (!("".equals(circleSn)))) {
            scope = "circlesn=?";
            paras.add(circleSn);
        }
        if ((dirId != null) && (!("".equals(dirId)))) {
            scope = scope + " and dirsn=?";
            paras.add(dirId);
        }
        if (date1 != null) {
            scope = scope + " and displaytime>=?";
            paras.add(date1);
        }
        if (date2 != null) {
            scope = scope + " and displaytime<?";
            paras.add(date2);
        }
        if ((query != null) && (!("".equals(query)))) {
            query = query.trim();
            query = query.replace("　", " ");
            query = query.replace("｜", "|");
            query = query.replace("，", ",");
            scope = scope + splitKeyWords(query, " ");
            scope = scope + splitKeyWords(query, "|");
            scope = scope + splitKeyWords(query, ",");
            if (!(this.keywordCanSplit)) {
                scope = scope + " and title like '%" + query + "%'";
            }
        }

        scope = scope + " order by displaytime desc";

        DbPageList pList = new DbPageList(BlogNewsDoc.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    private String splitKeyWords(String keywords, String seperator) {
        String keywordsSql = "";
        keywords = keywords.trim();
        if (keywords.contains(seperator)) {
            this.keywordCanSplit = true;
            String[] myquery = keywords.split(seperator);
            for (int i = 0; i < myquery.length; ++i) {
                keywordsSql = keywordsSql + " and title like '%" + myquery[i] + "%'";
            }
        }
        return keywordsSql;
    }

    public BlogNewsDoc readBlogNewsDoc(String cid) {
        BlogNewsDoc doc = getBlogNewsDoc(cid);
        doc.setReadtimes(doc.getReadtimes() + 1);
        updateBlogNewsDoc(doc);
        return doc;
    }

    public boolean updateBlogNewsDoc(BlogNewsDoc doc) {
        boolean ret = false;
        Date d = new Date();
        if ((doc.getDisplaytime() == null)
                || (doc.getDisplaytime().getTime() > d.getTime())) {
            doc.setDisplaytime(d);
        }
        ret = this.dao.update(doc);
        saveToHTML(doc);
        HTMLGenerater.saveToHTML(this.userService.getUserBlog(doc.getInputuser()));
        this.userService.blogInfoChange(this.userService.getUserBlog(doc.getInputuser()));
        return ret;
    }

    public boolean delBlogNewsDoc(String cid) {
        boolean ret = false;
        BlogNewsDoc doc = getBlogNewsDoc(cid);
        ret = this.dao.del(doc);
        if (ret) {
            BlogReviewServiceImpl.getInstance().delBlogReview(doc);
            BlogInfo blog = this.userService.getUserBlog(doc.getInputuser());
            removeHtmlFile(blog.getDomain(), doc);
            HTMLGenerater.saveToHTML(blog);
            this.userService.blogInfoChange(blog);
        }
        return ret;
    }

    public int delUserBlogNewsDoc(String username) {
        int ret = 0;
        String scope = "1=1";
        Collection<Object> paras = new ArrayList<Object>();
        if ((username != null) && (!("".equals(username)))) {
            scope = scope + " and inputuser=? ";
            paras.add(username);
        }else{
        	paras=null;
        }
        DbPageList pList = new DbPageList(BlogNewsDoc.class, scope, paras);
        pList.doList(0, -1);
        if (pList.getResult() != null) {
            List newsDoclist = pList.getResult();
            for(int i=0;i<newsDoclist.size();i++){
                BlogNewsDoc doc=(BlogNewsDoc)newsDoclist.get(i);
                boolean isdel=this.delBlogNewsDoc(doc.getCid());
                if(isdel){
                    ret++;
                }
            }
        }
        return ret;
    }

    public boolean generateBlogNewsDoc(String cid) {
        boolean ret = false;
        BlogNewsDoc doc = getBlogNewsDoc(cid);
        ret = HTMLGenerater.saveToHTML(doc);
        return ret;
    }

    public int batchGenerateBlogNewsDoc(String[] cids) {
        int ret = 0;
        for (int i = 0; i < cids.length; ++i) {
            if (generateBlogNewsDoc(cids[i])) {
                ++ret;
            }
        }
        return ret;
    }

    public boolean writeBlogDoc(BlogNewsDoc doc) {
        boolean ret = false;
        doc.setInputuser(CurrentUser.getActiveUser().getUserName());
        doc.setInputtime(new Date());
        doc.setReadtimes(new Integer(0));
        doc.setStatus(new Integer(0));
        ret = this.dao.save(doc);
        BlogInfo bloginfo = this.userService.getUserBlog(doc.getInputuser());
        doc.setUrl(doc.staticHtmlUrl());
        this.dao.update(doc);
        saveToHTML(doc);
        this.userService.blogInfoChange(bloginfo);
        HTMLGenerater.saveToHTML(this.userService.getUserBlog(doc.getInputuser()));
        return ret;
    }

    public List getTopBlogNewsDoc(String orderBy, int elite, int topNum) {
        String scope = "1=1";
        if (elite > 0) {
            scope = "elite>=" + elite;
        }
        scope = scope + " order by " + orderBy;
        Collection<Object> paras = new ArrayList<Object>();
        DbPageList pList = new DbPageList(BlogNewsDoc.class, scope, paras);
        pList.doList(0, topNum);
        return pList.getResult();
    }

    public List getTopBlogNewsDoc(String username, String dirId, Date date1, Date date2, String orderBy, int elite, int topNum) {
        String scope = "1=1";
        Collection<Object> paras = new ArrayList<Object>();
        if ((username != null) && (!("".equals(username)))) {
            scope = "inputuser=? ";
            paras.add(username);
        }
        if ((dirId != null) && (!("".equals(dirId)))) {
            scope = scope + " and dirsn=?";
            paras.add(dirId);
        }
        if (date1 != null) {
            scope = scope + " and displaytime>=?";
            paras.add(date1);
        }
        if (date2 != null) {
            scope = scope + " and displaytime<?";
            paras.add(date2);
        }
        scope = scope + " order by " + orderBy;
        DbPageList pList = new DbPageList(BlogNewsDoc.class, scope, paras);
        pList.doList(1, topNum);
        return pList.getResult();
    }

    public List getTopBlogNewsDocBySql(String sqlCondition, int topNum) {
        Collection<Object> paras = new ArrayList<Object>();
        DbPageList pList = new DbPageList(BlogNewsDoc.class, sqlCondition, paras);
        pList.doList(0, topNum);
        return pList.getResult();
    }

    public boolean saveToHTML(BlogNewsDoc obj) {
        boolean ret = false;
        try {
            ret = HTMLGenerater.saveToHTML(obj);
        } catch (Exception e) {
            System.out.println("保存静态文件错误！详见系统日志");
            logger.error(e);
        }
        return ret;
    }

    public String replaceEmotTag(String s) {
        String makeContent = new String();
        String[] r = new String[50];
        for (int i = 1; i < 50; ++i) {
            r[i] = "\\[em" + ((i < 10) ? "0" + i : new StringBuilder(String.valueOf(i)).toString()) + "\\]";
        }

        StringTokenizer strToken = new StringTokenizer(s, "\n");
        while (strToken.hasMoreTokens()) {
            makeContent = makeContent + "<br/>" + strToken.nextToken();
        }

        for (int i = 1; i < 50; ++i) {
            makeContent = makeContent.replaceAll(r[i],
                    "<img src=/images/emot/em" + ((i < 10) ? "0" + i : new StringBuilder(String.valueOf(i)).toString())
                    + ".gif/>");
        }

        r = (String[]) null;
        return makeContent;
    }

    public int getBlogNewsDocNum(String dirId, String username) {
        int retv = 0;
        String scope = "1=1";
        Collection<Object> paras = new ArrayList<Object>();
        if ((username != null) && (!("".equals(username)))) {
            scope = scope + " and inputuser=? ";
            paras.add(username);
        }
        if ((dirId != null) && (!("".equals(dirId)))) {
            scope = scope + " and dirsn=?";
            paras.add(dirId);
        }
        DbPageList pList = new DbPageList(BlogNewsDoc.class, scope, paras);
        pList.doList(0, -1);
        if(pList.getResult()!=null){
        	retv = pList.getResult().size();
        }
        return retv;
    }

    public int getBlogNewsDirNum(String username) {
        int retv = 0;
        String scope = "1=1";
        Collection<Object> paras = new ArrayList<Object>();
        if ((username != null) && (!("".equals(username)))) {
            scope = scope + " and inputuser=? ";
            paras.add(username);
        }
        DbPageList pList = new DbPageList(BlogNewsDir.class, scope, paras);
        pList.doList(0, -1);
        retv = pList.getResult().size();
        return retv;
    }

    public boolean removeHtmlFile(String domain, BlogNewsDoc doc) {
        String fileName = doc.getUrl();
        String filepath = Config.getWwwpath() + "/" + domain + fileName;
        return BlogFileUtil.removeFile(filepath);
    }

    public IPageList queryCircleNewsDoc(String circleSn, int currentPage, int pageSize) {
        return queryBlogNewsDoc(null, circleSn, null, null, null, null, currentPage, pageSize);
    }

    public static void main(String[] args) {
        //getInstance().queryBlogNewsDir("Elan2", 1, 1);
    }
}
